package com.wwj.my_ummary.config.webSocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket/socket/{userid}")
@Component
public class WebSocketServer {

    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    private String userid;

    @OnOpen
    public void onOPen(@PathParam("userid") String userid, Session session) {
        this.userid = userid;
        this.session = session;
        System.out.println("id:"+userid);
        webSocketSet.add(this); // 加入set中
		addOnlineCount(); // 在线数加1
		try {
			sendMessage("{\"msg\":\"success\"}");
		} catch (IOException e) {
		}
        pushMessage();
    }

    @OnMessage
    public void onMessage(String message, Session session) throws EncodeException, IOException {

		System.out.println("消息！" + message);
		System.out.println("当前在线人数！" + onlineCount);

    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this); // 从set中删除
		subOnlineCount(); // 在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    @OnError
    public void onErroe(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {

        this.session.getBasicRemote().sendText(message);

    }

    /**
     * 群发自定义消息
     */
    public void sendInfo(String message) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage(message);
        }
    }

    /**
     * 定向自定义消息
     */
    public void sendSomeoneInfo(String message, String someone) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            try {
                if (item.userid.equals(someone)) {
                    item.sendMessage(message);
                    System.out.println("开始推送信息到：" + someone);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    /**
     * 推送给在线用户
     */
    public static void pushMessage() {
//		CtcOrderService bean = SpringContextHolder.getBean(CtcOrderService.class);
//
//		String msg = bean.loadC2COrders();
//		for (WebSocketServer item : webSocketSet) {
//			try {
//				item.sendMessage(msg);
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}



//		Map map = (Map) SpringContextHolder.getBean(CtcOrderService.class);
//		CtcOrderService bean = (CtcOrderService) map.get("ctcOrderService");
//		String msg = bean.loadC2COrders();
//		for (WebSocketServer item : webSocketSet) {
//			try {
//				synchronized (item){
//					item.sendMessage(msg);
//				}
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
    }

}
